namespace DmServer.Core.Base;

/// <summary>
/// 
/// </summary>
public class ProcessUtil
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    /// <summary>
    /// 获取进程列表
    /// </summary>
    /// <param name="windowTitle">标题</param>
    /// <returns>进程名称数组</returns>
    public static List<ProcessInfo> GetProcess(string windowTitle)
    {
        var list = new List<ProcessInfo>(); 
        foreach (Process proc in Process.GetProcesses())
        {
            ProcessInfo processInfo = new ProcessInfo();

            if (proc.MainWindowTitle == windowTitle)
            {
                IntPtr hWnd = FindWindow(null, windowTitle);
                if (hWnd != IntPtr.Zero)
                {
                    processInfo.ProcessId = proc.Id;
                    processInfo.Hwnd = hWnd;
                    processInfo.MainWindowTitle = proc.MainWindowTitle;
                    list.Add(processInfo);
                }
            }
        }
        return list;
    }
}

/// <summary>
/// 进程信息
/// </summary>
public class ProcessInfo
{
    public int ProcessId { get; set; }
    public IntPtr Hwnd { get; set; }
    public string? MainWindowTitle { get; set; }
    public string? Title => MainWindowTitle + $"({ProcessId})";
}